package org.mms.service.impl;

import jakarta.transaction.Transactional;
import org.mms.exception.BusinessException;
import org.mms.pojo.entity.Permission;
import org.mms.pojo.entity.User;
import org.mms.repository.PermissionRepository;
import org.mms.repository.UserRepository;
import org.mms.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionRepository permissionRepository;
    @Autowired
    private UserRepository userRepository;

    @Override
    public List<Permission> findAll() {
        return permissionRepository.findAll();
    }

    @Override
    @Transactional
    public List<Permission> update(Long userId, List<String> permissionKeys) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new BusinessException("用户不存在"));

        if ("MANAGER".equals(user.getRole())) {
            throw new BusinessException("不能修改管理员权限");
        }

        permissionRepository.deleteByUserId(userId);

        return permissionRepository.saveAll(permissionKeys.stream()
                .map(key -> {
                    Permission perm = new Permission();
                    perm.setUserId(userId);
                    perm.setPermissionKey(key);
                    return perm;
                })
                .toList());
    }
}